//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.dstz.bpm.engine.action.handler.instance;

import com.dstz.base.api.exception.BusinessException;
import com.dstz.base.core.util.StringUtil;
import com.dstz.bpm.api.constant.ActionType;
import com.dstz.bpm.api.constant.InstanceStatus;
import com.dstz.bpm.api.constant.NodeType;
import com.dstz.bpm.api.model.def.IBpmDefinition;
import com.dstz.bpm.api.model.nodedef.BpmNodeDef;
import com.dstz.bpm.core.model.BpmInstance;
import com.dstz.bpm.engine.action.cmd.DefaultInstanceActionCmd;
import com.dstz.bpm.engine.action.handler.AbsActionHandler;
import org.springframework.stereotype.Component;

@Component
public class InstanceSaveActionHandler extends AbsActionHandler<DefaultInstanceActionCmd> {
   public InstanceSaveActionHandler() {
   }

   @Override
   protected void b(DefaultInstanceActionCmd model) {
      BpmInstance instance = (BpmInstance)model.getBpmInstance();
      instance.setStatus(InstanceStatus.STATUS_DRAFT.getKey());
   }


   @Override
   public void c(DefaultInstanceActionCmd data) {
      data.setBpmDefinition(this.a.getDefinitionById(data.getDefId()));
      this.g(data);
      this.m(data);
      this.a(data, this.a.getStartEvent(data.getDefId()));
   }

   @Override
   protected void e(DefaultInstanceActionCmd actionModel) {
      this.f(actionModel);
   }

   protected void f(DefaultInstanceActionCmd actionModel) {
      BpmInstance instance = (BpmInstance)actionModel.getBpmInstance();
      if (instance.hasCreate()) {
         this.f.update(instance);
      } else {
         this.f.create(instance);
      }

   }

   public void g(DefaultInstanceActionCmd intanceCmdData) {
      String instId = intanceCmdData.getInstanceId();
      BpmInstance instance = null;
      if (StringUtil.isNotEmpty(instId)) {
         instance = (BpmInstance)this.f.get(instId);
         if (StringUtil.isNotEmpty(instance.getActInstId())) {
            throw new BusinessException("草稿已经启动，请勿多次启动该草稿！");
         }
      }

      if (instance == null) {
         IBpmDefinition bpmDefinition = intanceCmdData.getBpmDefinition();
         instance = this.f.genInstanceByDefinition(bpmDefinition);
      }

      intanceCmdData.setBpmInstance(instance);
   }

   @Override
   protected void h(DefaultInstanceActionCmd var1) {

   }

   @Override
   protected void i(DefaultInstanceActionCmd var1) {
      //?
   }


   @Override
   public ActionType getActionType() {
      return ActionType.DRAFT;
   }

   @Override
   public int getSn() {
      return 2;
   }

   @Override
   public Boolean isSupport(BpmNodeDef nodeDef) {
      return nodeDef.getType() == NodeType.START ? true : false;
   }

   @Override
   public String getConfigPage() {
      return null;
   }

   public String getDefaultGroovyScript() {
      return "";
   }
}
